package com.maimang.platform.crm.controller;

import com.maimang.platform.annotation.Log;
import com.maimang.platform.base.BaseController;
import com.maimang.platform.base.Result;
import com.maimang.platform.common.config.RoleKeyConstant;
import com.maimang.platform.common.entity.SysDept;
import com.maimang.platform.common.entity.SysDeptTree;
import com.maimang.platform.common.entity.SysRole;
import com.maimang.platform.common.entity.SysUser;
import com.maimang.platform.common.service.SysDeptService;
import com.maimang.platform.common.service.SysUserService;
import com.maimang.platform.common.utils.ExcelUtil;
import com.maimang.platform.common.utils.ShiroUtils;
import com.maimang.platform.common.utils.excel.Column;
import com.maimang.platform.common.utils.excel.ExcelTool;
import com.maimang.platform.common.utils.excel.TitleEntity;
import com.maimang.platform.crm.entity.CrmWorkRecord;
import com.maimang.platform.crm.entity.WorkTreeNode;
import com.maimang.platform.crm.service.WorkExportService;
import com.maimang.platform.crm.service.WorkRecordService;
import com.maimang.platform.enums.BusinessType;
import com.maimang.platform.lang.StringUtils;
import com.maimang.platform.page.PageDomain;
import com.maimang.platform.page.TableDataInfo;
import com.maimang.platform.page.TableSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @author Rocky
 * @version 1.0.0
 * @classname WorkRecordController
 * @description <br>工作记录信息操作处理PC专用</br>
 * @date 2019-09-23 15:42:23
 * @email jintaozhao@qq.com
 */
@Controller
@RequestMapping("/crm/work")
@Api(value = "工作记录-PC", description = "工作记录 信息操作处理接口")
public class WorkPcController extends BaseController {
	private String prefix = "crm/work";

	@Autowired
	private WorkRecordService workRecordService;

	@Autowired
	private WorkExportService workExportService;

	@Autowired
	private SysDeptService deptService;

	@Autowired
	private SysUserService userService;

	@ApiIgnore
	@RequiresPermissions("crm:work:view")
	@GetMapping("/statistic")
	public String statistic(ModelMap modelMap, HttpServletResponse response) {
		// 取身份信息
		SysUser user = getSysUser();
		String roleKey = StringUtils.EMPTY;
		for (SysRole role : user.getRoles()) {
			if (StringUtils.isEmpty(roleKey))
				roleKey = role.getRoleKey();
			else
				roleKey.concat("," + role.getRoleKey());
		}
		modelMap.put("user", user);
		modelMap.put("roleKey", roleKey);
		return prefix + "/statistic";
	}

	@ApiIgnore
	@RequiresPermissions("crm:work:view")
	@GetMapping()
	public String workRecord(ModelMap modelMap, HttpServletResponse response) {
		// 取身份信息
		SysUser user = getSysUser();
		String roleKey = StringUtils.EMPTY;
		for (SysRole role : user.getRoles()) {
			if (StringUtils.isEmpty(roleKey))
				roleKey = role.getRoleKey();
			else
				roleKey.concat("," + role.getRoleKey());
		}
		modelMap.put("user", user);
		modelMap.put("roleKey", roleKey);
		return prefix + "/record";
	}

	/**
	 * 查询工作记录列表
	 */
	@ApiOperation(value = "查询列表", notes = "查询工作记录列表信息")
	@RequiresPermissions("crm:work:list")
	@PostMapping("/list")
	@ResponseBody
	public TableDataInfo list(CrmWorkRecord workRecord) {
		SysUser user = ShiroUtils.getSysUser();
		for (SysRole role : user.getRoles()) {
			String roleKey = role.getRoleKey();
			if (roleKey.equalsIgnoreCase(RoleKeyConstant.ADMIN) || roleKey.equalsIgnoreCase(RoleKeyConstant.MASTER_ADMIN) || roleKey.equalsIgnoreCase(RoleKeyConstant.SUB_ADMIN)) {
				SysUser sysUser = new SysUser();
				if (StringUtils.isNotNull(workRecord.getDeptId()))
					sysUser.setDeptId(workRecord.getDeptId());
				else
					sysUser.setDeptId(1L);
				break;
			}
			if (roleKey.equalsIgnoreCase(RoleKeyConstant.EMPLOYEE)) {
				workRecord.setUserName(user.getUserName());
			}
			if (roleKey.equalsIgnoreCase(RoleKeyConstant.MANAGER)) {
				workRecord.setDeptId(user.getDeptId());
			}
			if (roleKey.equalsIgnoreCase(RoleKeyConstant.HRBP01)) {

			}
		}
		startPage();
		List<CrmWorkRecord> list = workRecordService.selectWorkRecordList(workRecord);
		return getDataTable(list);
	}


	/**
	 * 导出工作记录列表
	 */
	@ApiOperation(value = "导出列表", notes = "导出工作统计信息到Excel文件")
	@RequiresPermissions("crm:work:export")
	@PostMapping("/export")
	@ResponseBody
	public Result export(Long deptId, String deptName, String isNew, Date startTime, Date endTime) throws Exception {
		if (StringUtils.isNull(deptId) || deptId == 0) {
			return error("部门选择不正确");
		}
		List<SysDeptTree> children = deptService.selectChildren(deptId);
		if (children.size() != 0) {
			return error("所选择部门有下属部门，请重新选择");
		}
		if (StringUtils.isNull(startTime) || StringUtils.isNull(endTime)) {
			return error("时间选择不正确");
		}
		Map<String, List<Map<String, Object>>> tableData = workExportService.workStatistics(deptId, isNew, startTime, endTime);
		Map<String, String> sheetNames = workExportService.getSheetNames(deptId);
		ExcelTool excelTool = new ExcelTool(sheetNames, 10, 20);
		List<TitleEntity> titleEntityList = workExportService.createTitleList(deptId, startTime, endTime);
		List<Column> titleData = excelTool.columnTransformer(titleEntityList, "id", "pid", "content", "fieldName", "0");
		Map<String, List<Column>> columnsMap = new LinkedHashMap<>();
		for (String key : tableData.keySet()) {
			columnsMap.put(key, titleData);
		}

		Result result = excelTool.exportExcel("引领性指标报表_" + deptName, columnsMap, tableData, true, true);
		return result;
	}

	/**
	 * 导出工作记录列表
	 */
	@ApiOperation(value = "导出报表", notes = "导出工作统计信息到Excel文件")
	@RequiresPermissions("crm:work:export")
	@PostMapping("/exportExcel")
	@ResponseBody
	public Result exportExcel(Long deptId, String deptName, Date startTime, Date endTime) throws Exception {
		if (StringUtils.isNull(deptId) || deptId == 0L) {
			return error("请选择部门");
		}
		SysDept dept = deptService.selectDeptById(deptId);
		if (StringUtils.isNotNull(dept)) {
			String[] depts = dept.getAncestors().split(",");
			if (depts.length > 3)
				return error("所选部门没有下级部门，请重新选择");
		}

		if (StringUtils.isNull(startTime) || StringUtils.isNull(endTime)) {
			return error("时间选择不正确");
		}

		// 处理下起始与结束时间
		startTime = initStartDate(startTime);
		endTime = initEndDate(endTime);
		// 获取sheet页名称map
		Map<String, String> sheetNameMap = workExportService.createSheetNames();
		// 创建Excel导出工具类实例
		ExcelTool excelTool = new ExcelTool(sheetNameMap, 20, 20);
		// 创建sheet页表头信息map
		Map<String, List<TitleEntity>> titleList = workExportService.createTitles(sheetNameMap, startTime, endTime);
		// 表头数据转化为列
		Map<String, List<Column>> columnsMap = excelTool.columnsTransformer(titleList, "id", "pid", "content", "fieldName", "0");
		// 查询Excel body部分数据
		Map<String, List<Map<String, Object>>> tableData = workExportService.statistics(sheetNameMap, deptId, startTime, endTime);
		// 将表头与主体数据传入工具类进行Excel写入并导出
		Result result = excelTool.exportExcel("引领性指标报表_" + deptName, columnsMap, tableData, true, true);
		return result;
	}

	/**
	 * 初始化开始与结束时间
	 * 前台传递过来的日期只有日期，没有时分秒
	 *
	 * @param startTime 开始时间
	 */
	private Date initStartDate(Date startTime) {
		Calendar startCal = Calendar.getInstance();
		startCal.setTime(startTime);
		// 将时分秒,毫秒域清零
		startCal.set(Calendar.HOUR_OF_DAY, 0);
		startCal.set(Calendar.MINUTE, 0);
		startCal.set(Calendar.SECOND, 0);
		return startCal.getTime();
	}

	/**
	 * 初始化开始与结束时间
	 * 前台传递过来的日期只有日期，没有时分秒
	 *
	 * @param endTime 结束时间
	 */
	private Date initEndDate(Date endTime) {
		Calendar endCal = Calendar.getInstance();
		endCal.setTime(endTime);
		// 将时分秒,毫秒域清零
		endCal.set(Calendar.HOUR_OF_DAY, 23);
		endCal.set(Calendar.MINUTE, 59);
		endCal.set(Calendar.SECOND, 59);
		return endCal.getTime();
	}

	/**
	 * 新增工作记录
	 */
	@ApiIgnore
	@GetMapping("/add")
	public String add() {
		return prefix + "/add";
	}

	/**
	 * 新增保存工作记录
	 */
	@ApiOperation(value = "新增保存", notes = "参数：CrmWorkRecord")
	@RequiresPermissions("crm:work:add")
	@Log(title = "工作记录", businessType = BusinessType.INSERT)
	@PostMapping("/add")
	@ResponseBody
	public Result addSave(CrmWorkRecord workRecord) {
		return toResult(workRecordService.insertWorkRecord(workRecord));
	}

	/**
	 * 修改工作记录
	 */
	@ApiIgnore
	@GetMapping("/edit/{workId}")
	public String edit(@PathVariable("workId") Integer workId, ModelMap modelMap) {
		CrmWorkRecord workRecord = workRecordService.selectWorkRecordById(workId);
		modelMap.put("workRecord", workRecord);
		return prefix + "/edit";
	}

	@ApiOperation(value = "获取详情", notes = "参数：workId")
	@RequiresPermissions("crm:work:edit")
	@Log(title = "工作记录", businessType = BusinessType.UPDATE)
	@GetMapping("/detail/{workId}")
	@ResponseBody
	public Result<CrmWorkRecord> getRecordById(@PathVariable("workId") Integer workId) {
		try {
			CrmWorkRecord workRecord = workRecordService.selectWorkRecordById(workId);
			return Result.SUCCESS(workRecord);
		} catch (Exception e) {
			return error("服务器出小差了~请稍后再试");
		}
	}

	/**
	 * 修改保存工作记录
	 */
	@ApiOperation(value = "修改保存", notes = "参数：CrmWorkRecord")
	@RequiresPermissions("crm:work:edit")
	@Log(title = "工作记录", businessType = BusinessType.UPDATE)
	@PostMapping("/edit")
	@ResponseBody
	public Result editSave(CrmWorkRecord workRecord) {
		return toResult(workRecordService.updateWorkRecord(workRecord));
	}

	/**
	 * 删除工作记录
	 */
	@ApiOperation(value = "删除对象", notes = "参数：ids，示例： id1,id2,id3，接口会转转为String[]类型")
	@RequiresPermissions("crm:work:remove")
	@Log(title = "工作记录", businessType = BusinessType.DELETE)
	@PostMapping("/remove")
	@ResponseBody
	public Result remove(String ids) {
		return toResult(workRecordService.deleteWorkRecordByIds(ids));
	}

	@ApiOperation(value = "工作统计", notes = "参数：userId, deptId, type, start, end")
	@RequiresPermissions("crm:work:list")
	@Log(title = "工作统计", businessType = BusinessType.UPDATE)
	@PostMapping("/statistic")
	@ResponseBody
	public TableDataInfo getWorkStatistics(@RequestParam(name = "userId") Long userId,
	                                       @RequestParam(name = "deptId") Long deptId,
	                                       @RequestParam(name = "type") String type,
	                                       @RequestParam(name = "start") Date startDate,
	                                       @RequestParam(name = "end") Date endDate) {
		startPage();
		List<WorkTreeNode> treeNodeList = workRecordService.workStatistics(userId, deptId, type, startDate, endDate);
		return getDataTable(treeNodeList);
	}


	/**
	 * 查询工作记录列表
	 */
	@ApiOperation(value = "统计信息", notes = "查询工作记录攻击--PC专用")
	@RequiresPermissions("crm:work:list")
	@PostMapping("/worklist")
	@ResponseBody
	public TableDataInfo worklist(WorkTreeNode workTreeNode) {
		startPage();
		List<WorkTreeNode> list = workRecordService.workStatistics(workTreeNode.getUserId(), workTreeNode.getDeptId(), workTreeNode.getType(), workTreeNode.getStartDate(), workTreeNode.getEndDate());
		return getDataTable1(list);
	}


	/**
	 * 导出工作日志详情列表
	 */
	@ApiOperation(value = "导出列表", notes = "导出工作日志详情列表信息到Excel文件")
	@RequiresPermissions("crm:work:export")
	@PostMapping("/workExport")
	@ResponseBody
	public Result workExport(CrmWorkRecord workRecord) {
		List<CrmWorkRecord> list = workRecordService.selectWorkRecordList(workRecord);
		ExcelUtil<CrmWorkRecord> util = new ExcelUtil<>(CrmWorkRecord.class);
		return util.exportExcel(list, "工作日志详情");
	}
}